//
// server.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the GNU Affero General Public License, Version 3.0. (See accompanying
// file LICENSE or copy at http://www.gnu.org/licenses/agpl-3.0.txt)
//

#ifndef HTTP_AVIM_SERVER_SERVER_HPP
#define HTTP_AVIM_SERVER_SERVER_HPP

#include <boost/asio.hpp>
#include <string>
#include <list>
#include <boost/array.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include "request_parser.hpp"

namespace http {
namespace avim_server {

struct request;
struct reply;

/// The top-level coroutine of the HTTP server.
class server : boost::asio::coroutine
{
public:
	///定义模块Handler的回调函数, 具体介绍如下:
	// 参数 request 包含了客户端的请求信息.
	// 参数 reply 包含了模块处理后的回复信息.
	// 返回bool值, 如果返回true, 表示这个模块接受并处理了这个request, 这时server不会再尝试使用
	// 其它模块处理这个request.
	// 如果返回false, 则表示这个模块不能处理这个模块, 这时server将继续尝试其它moudle处理这个request.
	// 如果所有模块都不能处理这个request, 将返回默认的reply给客户端.
	typedef boost::function<bool(const request&, reply&)> module_handler;
	/// 定义模块链表类型.
	typedef std::list<module_handler> im_modules;

public:
	/// Construct the server to listen on the specified TCP address and port, and
	/// serve up files from the given directory.
	explicit server(boost::asio::io_service& io_service,
		const std::string& address, const std::string& port,
		im_modules request_handlers);

	/// Perform work associated with the server.
	void operator()(
		boost::system::error_code ec = boost::system::error_code(),
		std::size_t length = 0);

private:
	typedef boost::asio::ip::tcp tcp;

	/// The user-supplied handler for all incoming requests.
	im_modules request_handler_;

	/// Acceptor used to listen for incoming connections.
	boost::shared_ptr<tcp::acceptor> acceptor_;

	/// The current connection from a client.
	boost::shared_ptr<tcp::socket> socket_;

	/// Buffer for incoming data.
	boost::shared_ptr<boost::array<char, 8192> > buffer_;

	/// The incoming request.
	boost::shared_ptr<request> request_;

	/// Whether the request is valid or not.
	boost::tribool valid_request_;

	/// The parser for the incoming request.
	request_parser request_parser_;

	/// The reply to be sent back to the client.
	boost::shared_ptr<reply> reply_;
};

} // namespace avim_server
} // namespace http

#endif // HTTP_AVIM_SERVER_SERVER_HPP
